#define  _CRT_SECURE_NO_WARNINGS
#include "queue.h"

void print(Queue* pq)
{
	assert(pq);
	ListNode* tmp = pq->phead;
	while (tmp != nullptr)
	{
		cout << tmp->val << "->";
		tmp = tmp->next;
	}
	cout << endl;
}

void QueueInit(Queue* pq)
{
	assert(pq);
	pq->phead = nullptr;
	pq->ptail = nullptr;
	pq->size = 0;
}

ListNode* BuyNewNode(int x)
{
	ListNode* node = (ListNode*)malloc(sizeof(ListNode));
	assert(node);
	node->next = nullptr;
	node->val = x;
	return node;
}

void QueuePush(Queue* pq, int x)
{
	assert(pq);
	ListNode* newnode = BuyNewNode(x);
	
	if (nullptr == pq->phead)
	{
		pq->phead = newnode;
		pq->ptail = newnode;
		pq->size++;
	}
	else
	{
		ListNode* tmp = pq->ptail;
		tmp->next = newnode;
		tmp = tmp->next;
		pq->ptail = tmp;
		pq->size++;
	}
}

void QueuePop(Queue* pq)
{
	assert(pq);
	assert(pq->phead);
	if (pq->phead == pq->ptail)
	{
		free(pq->phead);
		pq->phead = nullptr;
	}
	else
	{
		ListNode* tmp = pq->phead;
		pq->phead = tmp->next;
		free(tmp);
		tmp = nullptr;
	}
	pq->size--;
}


int QueueFront(Queue* pq)
{
	assert(pq);
	assert(pq->phead);
	return pq->phead->val;
}

int QueueBack(Queue* pq)
{
	assert(pq);
	assert(pq->phead);

	return pq->ptail->val;
}

bool QueueEmpty(Queue* pq)
{
	assert(pq);
	return pq->phead == nullptr;
}

int QueueSize(Queue* pq)
{
	assert(pq);
	return pq->size;
}

void QueueDestroy(Queue* pq)
{
	assert(pq);
	ListNode* tmp = pq->phead;
	while (tmp)
	{
		ListNode* next = tmp->next;
		free(tmp);
		tmp = next;
	}
	pq->phead = pq->ptail = nullptr;
}